#include <gflags/gflags.h>
#include <iostream>
#include <memory>
#include<vector>
#include <sw/redis++/redis++.h>

DEFINE_string(server_ip, "127.0.0.1", "这是服务器的监听地址，格式为[0.0.0.0]");
DEFINE_int32(server_port, 6379, "这是redis服务器的监听端口，格式为[6379]");
DEFINE_bool(keep_alive, true, "是否启用长连接保活，格式为[true/false]");
DEFINE_int32(db, 0, "库的编号，默认为0");

void add_string(sw::redis::Redis *client)
{
    client->set("会话1", "用户1");
    client->set("会话2", "用户2");
    client->set("会话3", "用户3");
    client->set("会话4", "用户4");
    client->set("会话5", "用户5");

    client->del("会话2");
    auto user1 = client->get("会话1");
    if (user1)
    {
        std::cout << *user1 << std::endl;
    }
    auto user2 = client->get("会话2");
    if (user2)
    {
        std::cout << *user2 << std::endl;
    }
    auto user3 = client->get("会话3");
    if (user3)
    {
        std::cout << *user3 << std::endl;
    }
}

void expired_test(sw::redis::Redis *client)
{
    // 数据如果存在再次set是覆盖
    client->set("会话4", "用户4", std::chrono::seconds(1)); // 这时多设置了一个过期时间1s，具体应用：验证码
    client->set("会话5", "用户5", std::chrono::seconds(100));
}

void add_list(sw::redis::Redis *client)
{
    client->rpush("群聊1", "成员1");
    client->rpush("群聊1", "成员2");
    client->rpush("群聊1", "成员3");
    std::vector<std::string> users;
    client->lrange("群聊1", 0, -1, std::back_inserter(users));
    for (auto user : users)
    {
        std::cout << user << std::endl;
    }
}

int main(int argc, char *argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);

    // 构造连接选项
    sw::redis::ConnectionOptions opts;
    opts.host = FLAGS_server_ip;
    opts.port = FLAGS_server_port;
    opts.db = FLAGS_db;
    opts.keep_alive = FLAGS_keep_alive;
    // 实例化redis对象
    auto client = std::make_shared<sw::redis::Redis>(opts);

    // 新增字符串键值对、调整过期时间
    add_string(client.get());
    expired_test(client.get());

    // 列表数据新增
    add_list(client.get());
    return 0;
}